 package com.briup.cms.log;

import com.briup.cms.bean.BaseLog;
 import com.briup.cms.log.LoggingAccessPersisting;
 import com.briup.cms.utils.SecurityUtils;
 import java.lang.reflect.Method;
 import java.util.Date;
 import org.aspectj.lang.ProceedingJoinPoint;
 import org.aspectj.lang.annotation.Around;
 import org.aspectj.lang.annotation.Aspect;
 import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

 @Aspect
 public class LoggingAccessAspectResolver
 {
  private static final Logger LOGGER = LoggerFactory.getLogger(com.briup.cms.log.LoggingAccessAspectResolver.class);

  private LoggingAccessPersisting loggingAccessPersisting;

   public LoggingAccessAspectResolver(LoggingAccessPersisting loggingAccessPersisting) {
     this.loggingAccessPersisting = loggingAccessPersisting;
  }

 @Pointcut("execution(* com.briup.cms.web.controller.*.*(..)) && @annotation(LoggingAccess)")
  public void loggingPoincut() {}
 @Around("loggingPoincut()")
   public Object loggingAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    MethodSignature methodSignature = (MethodSignature)proceedingJoinPoint.getSignature();
    Method method = methodSignature.getMethod();

    BaseLog log = new BaseLog();

    setloggingInfo(log);
     try {
       this.loggingAccessPersisting.persist(log);
    } catch (Exception exception) {
       LOGGER.error("An exception[{}] occurred while saving the log", exception);
    }

    return proceedingJoinPoint.proceed();
  }

  private void setloggingInfo(BaseLog log) {
    log.setLogUsername(SecurityUtils.getUsername());
    log.setLogRealname(SecurityUtils.getRealname());
    log.setLogRequestMethod(SecurityUtils.getmethod());
    log.setLogRequestUri(SecurityUtils.getRequestURI());
   log.setLogTime(new Date());
  }
}


